#include <iostream>
#include <GL/glew.h>
#include <SFML/Window.hpp>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif

#include "Event.h"
#include "CanvasDesktopGL.h"

#define DEFAULT_GL_MAJOR_VERSION 2
#define DEFAULT_GL_MINOR_VERSION 1

namespace SypX
{
	CanvasDesktopGL::CanvasDesktopGL(SypX::UInt width, SypX::UInt height, SypX::UInt color, SypX::UInt depth, bool fullscreen):Canvas(width, height, color, depth, fullscreen)
	{
		sfmlApp = new sf::Window(sf::VideoMode(width, height, color), "SypX", fullscreen ? sf::Style::Fullscreen : sf::Style::Titlebar|sf::Style::Resize|sf::Style::Close);
		sfmlApp->UseVerticalSync(false);
		//sfmlApp->SetFramerateLimit(85);
	}

	///Returns an event from the Event que
	Event CanvasDesktopGL::getEvent()
	{
		sf::Event ev;
		Event e;

		do
		{
			if(!sfmlApp->GetEvent(ev))
			{
				e.type = NOEVENTS;
				return e;
			}
			switch(ev.Type)
			{
			case sf::Event::MouseButtonPressed:
				if(ev.MouseButton.Button == sf::Mouse::Left)
				{
					e.type = MOUSELEFTDOWN;
				}
				else if(ev.MouseButton.Button == sf::Mouse::Right)
				{
					e.type = MOUSERIGHTDOWN;
				}
				e.location.x = ev.MouseButton.X;
				e.location.y = height - ev.MouseButton.Y;
				return e;
				break;
			case sf::Event::MouseButtonReleased:
				if(ev.MouseButton.Button == sf::Mouse::Left)
				{
					e.type = MOUSELEFTUP;
				}
				else if(ev.MouseButton.Button == sf::Mouse::Right)
				{
					e.type = MOUSERIGHTUP;
				}
				e.location.x = ev.MouseButton.X;
				e.location.y = height - ev.MouseButton.Y;
				return e;
				break;
			case sf::Event::MouseMoved:
				e.type = MOUSEMOVE;
				e.moved.curr.x = ev.MouseMove.X;
				e.moved.curr.y = height - ev.MouseMove.Y;
				return e;
				break;
			case sf::Event::Closed:
				sfmlApp->Close();
				break;
			default:
				break;
			}
		}while(true);

	}

	void CanvasDesktopGL::resetCanvas(SypX::UInt width, SypX::UInt height, SypX::UInt color, SypX::UInt depth, bool fullscreen)
	{
		Canvas::resetCanvas(width, height, color, depth, fullscreen);//Call Base class to record new settings first

		//Recreate canvas
		sfmlApp->Create(sf::VideoMode(width, height, color), "SypX", fullscreen ? sf::Style::Fullscreen : sf::Style::Close);
	}

	void CanvasDesktopGL::resize(UInt width, UInt height)
	{
		Canvas::resize(width, height);
		sfmlApp->SetSize(width, height);
	}

	bool CanvasDesktopGL::isOpen()
	{
		return sfmlApp->IsOpened();
	}

	float CanvasDesktopGL::getElapsedTime()
	{
		return sfmlApp->GetFrameTime();
	}



	CanvasDesktopGL::~CanvasDesktopGL()
	{
		delete sfmlApp;
	}

	void CanvasDesktopGL::swapBuffers()
	{
		sfmlApp->Display();
	}

}
